<template>
  <view class="filter-menu">
    <!-- 筛选标题栏 -->
    <view class="filter-header">
      <view 
        v-for="(item, index) in menuList" 
        :key="index"
        class="filter-title"
        :class="{ active: currentTab === index }"
        @tap="handleTabClick(index)"
      >
        <text>{{ item.title }}</text>
        <up-icon :name="currentTab === index ? 'arrow-up' : 'arrow-down'" size="12"></up-icon>
      </view>
    </view>

    <!-- 筛选内容区 -->
    <view 
      class="filter-content" 
      :class="{ 'content-show': showContent }"
      v-show="showContent"
    >
      <!-- 树形筛选 -->
      <view v-if="menuList[currentTab]?.type === 'tree'" class="tree-filter">
        <view class="tree-wrapper">
          <!-- 第一层 -->
          <scroll-view scroll-y class="tree-column">
            <view
              v-for="(item, index) in treeData"
              :key="index"
              class="tree-item"
              :class="{ active: item.id === selectedLevel1 }"
              @tap="handleLevel1Click(item)"
            >{{ item.name }}</view>
          </scroll-view>
          
          <!-- 第二层 -->
          <scroll-view scroll-y class="tree-column" v-if="level2Data.length">
            <view
              v-for="(item, index) in level2Data"
              :key="index"
              class="tree-item"
              :class="{ active: item.id === selectedLevel2 }"
              @tap="handleLevel2Click(item)"
            >{{ item.name }}</view>
          </scroll-view>
          
          <!-- 第三层 -->
          <scroll-view scroll-y class="tree-column" v-if="level3Data.length">
            <view
              v-for="(item, index) in level3Data"
              :key="index"
              class="tree-item"
              :class="{ active: selectedItems.includes(item.id) }"
              @tap="handleLevel3Click(item)"
            >{{ item.name }}</view>
          </scroll-view>
        </view>
        <view class="checkbox-footer">
          <view class="btn-reset" @tap="handleResetTree">重置</view>
          <view class="btn-confirm" @tap="handleConfirm">确定</view>
        </view>
      </view>

      <!-- 单选筛选 -->
      <view v-if="menuList[currentTab]?.type === 'radio'" class="radio-filter">
        <view class="menuBtnsWwrap">
          <view
            v-for="(item, index) in menuList[currentTab].data"
            :key="index"
            class="radio-item"
            :class="{ active: selectedRadio === item.value }"
            @tap="handleRadioClick(item)"
          >{{ item.name }}</view>
        </view>
        <view class="checkbox-footer">
          <view class="btn-reset" @tap="handleReset">重置</view>
          <view class="btn-confirm" @tap="handleConfirm">确定</view>
        </view>
      </view>

      <!-- 多选筛选 -->
      <view v-if="menuList[currentTab]?.type === 'checkbox'" class="checkbox-filter">
        <view class="menuBtnsWwrap">
          <view
            v-for="(item, index) in menuList[currentTab].data"
            :key="index"
            class="checkbox-item"
            :class="{ active: selectedCheckbox.includes(item.value) }"
            @tap="handleCheckboxClick(item)"
          >{{ item.name }}</view>
        </view>

        <!-- 多选底部按钮 -->
        <view class="checkbox-footer">
          <view class="btn-reset" @tap="handleReset">重置</view>
          <view class="btn-confirm" @tap="handleConfirm">确定</view>
        </view>
      </view>
    </view>

    <!-- 遮罩层 -->
    <view 
      class="mask" 
      :class="{ 'mask-show': showContent }"
      :style="{ top: maskTop + 'px' }"
      v-show="showContent" 
      @tap="handleMaskClick"
    ></view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

const props = defineProps({
  menuList: {
    type: Array,
    default: () => []
  },
  defaultValues: {
    type: Array,
    default: () => []
  },
  maskTop: {
    type: Number,
    default: 0
  }
});

const emit = defineEmits(['change', 'update:modelValue', 'filterOpen', 'filterClose']);

// 控制显示状态
const showContent = ref(false);
const currentTab = ref(-1);

// 树形选择相关数据
const selectedLevel1 = ref('');
const selectedLevel2 = ref('');
const selectedItems = ref([]);
const treeData = ref([]);
const level2Data = computed(() => {
  const selected = treeData.value.find(item => item.id === selectedLevel1.value);
  return selected?.children || [];
});
const level3Data = computed(() => {
  const selected = level2Data.value.find(item => item.id === selectedLevel2.value);
  return selected?.children || [];
});

// 单选数据
const selectedRadio = ref('');

// 多选数据
const selectedCheckbox = ref([]);

// 选中值存储
const selectedValues = ref([]);

// 添加临时存储值
const tempCheckboxValue = ref([]);

// 初始化默认值
function initDefaultValues() {
  selectedValues.value = new Array(props.defaultValues.length).fill(null);
  
  props.defaultValues.forEach((value, index) => {
    const menuItem = props.menuList[index];
    if (!menuItem) return;

    switch (menuItem.type) {
      case 'tree':
        selectedValues.value[index] = value || { level1: '', level2: '', items: [] };
        if (currentTab.value === index) {
          selectedLevel1.value = value?.level1 || '';
          selectedLevel2.value = value?.level2 || '';
          selectedItems.value = value?.items || [];
        }
        break;
      case 'radio':
        selectedValues.value[index] = value || '';
        if (currentTab.value === index) {
          selectedRadio.value = value || '';
        }
        break;
      case 'checkbox':
        selectedValues.value[index] = Array.isArray(value) ? [...value] : [];
        if (currentTab.value === index) {
          tempCheckboxValue.value = Array.isArray(value) ? [...value] : [];
          selectedCheckbox.value = Array.isArray(value) ? [...value] : [];
        }
        break;
    }
  });
}

// 监听默认值变化
watch(() => props.defaultValues, (newVal) => {
  initDefaultValues();
}, { deep: true });

// 更新选中值
function updateSelectedValue(index, value) {
  // 确保更新的是正确的数组位置
  if (index >= 0 && index < selectedValues.value.length) {
    selectedValues.value[index] = value;
  }
}

// 监听菜单列表变化，初始化树形数据
watch(() => props.menuList, (newVal) => {
  const treeItem = newVal.find(item => item.type === 'tree');
  if (treeItem) {
    treeData.value = treeItem.data;
  }
  // 重新初始化默认值
  initDefaultValues();
}, { immediate: true });

// 处理标题点击
function handleTabClick(index) {
  if (currentTab.value === index) {
    showContent.value = false;
    currentTab.value = -1;
    emit('filterClose');
  } else {
    // 如果之前有打开的标签，需要重置未确认的状态
    if (currentTab.value !== -1) {
      resetUnconfirmedState(currentTab.value);
    }
    
    // 设置新的标签页
    showContent.value = true;
    currentTab.value = index;
    
    // 根据类型初始化当前标签的状态
    initCurrentTabState(index);
    
    emit('filterOpen');
  }
}

// 重置未确认的状态
function resetUnconfirmedState(index) {
  const menuItem = props.menuList[index];
  if (!menuItem) return;

  switch (menuItem.type) {
    case 'checkbox':
      // 重置为已确认的值
      selectedCheckbox.value = selectedValues.value[index] || [];
      tempCheckboxValue.value = [...selectedCheckbox.value];
      break;
    case 'radio':
      selectedRadio.value = selectedValues.value[index] || '';
      break;
    case 'tree':
      const confirmedValue = selectedValues.value[index] || { level1: '', level2: '', items: [] };
      selectedLevel1.value = confirmedValue.level1;
      selectedLevel2.value = confirmedValue.level2;
      selectedItems.value = [...(confirmedValue.items || [])];
      break;
  }
}

// 初始化当前标签状态
function initCurrentTabState(index) {
  const menuItem = props.menuList[index];
  if (!menuItem) return;

  switch (menuItem.type) {
    case 'checkbox':
      selectedCheckbox.value = selectedValues.value[index] || [];
      tempCheckboxValue.value = [...selectedCheckbox.value];
      break;
    case 'radio':
      selectedRadio.value = selectedValues.value[index] || '';
      break;
    case 'tree':
      const value = selectedValues.value[index] || { level1: '', level2: '', items: [] };
      selectedLevel1.value = value.level1;
      selectedLevel2.value = value.level2;
      selectedItems.value = [...(value.items || [])];
      break;
  }
}

// 树形选择处理
function handleLevel1Click(item) {
  selectedLevel1.value = item.id;
  selectedLevel2.value = '';
  selectedItems.value = [];
  updateSelectedValue(currentTab.value, {
    level1: item.id,
    level2: '',
    items: []
  });
}

function handleLevel2Click(item) {
  selectedLevel2.value = item.id;
  selectedItems.value = [];
  updateSelectedValue(currentTab.value, {
    level1: selectedLevel1.value,
    level2: item.id,
    items: []
  });
}

function handleLevel3Click(item) {
  const index = selectedItems.value.indexOf(item.id);
  if (index > -1) {
    selectedItems.value.splice(index, 1);
  } else {
    selectedItems.value.push(item.id);
  }
  updateSelectedValue(currentTab.value, {
    level1: selectedLevel1.value,
    level2: selectedLevel2.value,
    items: selectedItems.value
  });
}

// 单选处理
function handleRadioClick(item) {
  selectedRadio.value = item.value;
  updateSelectedValue(currentTab.value, item.value);
}

// 多选处理
function handleCheckboxClick(item) {
  let newValue = [];
  if (item.value === '') {
    newValue = [item.value];
  } else {
    const currentValue = tempCheckboxValue.value || [];
    if (Array.isArray(currentValue)) {
      if (currentValue.includes(item.value)) {
        newValue = currentValue.filter(v => v !== item.value);
      } else {
        newValue = [...currentValue.filter(v => v !== ''), item.value];
      }
    }
  }
  tempCheckboxValue.value = newValue;
  selectedCheckbox.value = newValue;
}

// 重置树形菜单
function handleResetTree() {
  // 重置所有层级的选择状态
  selectedLevel1.value = '1';
  selectedLevel2.value = '';
  selectedItems.value = [];
  
  // 更新选中值
  updateSelectedValue(currentTab.value, {
    level1: '1',
    level2: '',
    items: []
  });
}

// 重置处理
function handleReset() {
  if (props.menuList[currentTab.value]?.type === 'checkbox') {
    tempCheckboxValue.value = [];
    selectedCheckbox.value = [];
  } else {
    updateSelectedValue(currentTab.value, []);
    selectedRadio.value = '';
  }
}

// 确认按钮处理
function handleConfirm() {
  // 更新当前选中的值到对应位置
  if (props.menuList[currentTab.value]?.type === 'checkbox') {
    selectedValues.value[currentTab.value] = tempCheckboxValue.value;
  } else if (props.menuList[currentTab.value]?.type === 'radio') {
    selectedValues.value[currentTab.value] = selectedRadio.value;
  } else if (props.menuList[currentTab.value]?.type === 'tree') {
    selectedValues.value[currentTab.value] = {
      level1: selectedLevel1.value,
      level2: selectedLevel2.value,
      items: selectedItems.value
    };
  }

  // 发送变更事件，返回所有选中值
  emit('change', {
    index: currentTab.value,
    value: selectedValues.value[currentTab.value],
    allValues: selectedValues.value  // 返回完整的数组，保持与 defaultValues 相同的顺序
  });
  
  closeMenu();
}

// 关闭菜单方法
function closeMenu() {
  // 如果是多选且未点击确认，恢复到之前的选中状态
  if (props.menuList[currentTab.value]?.type === 'checkbox') {
    selectedCheckbox.value = selectedValues.value[currentTab.value] || [];
    tempCheckboxValue.value = selectedCheckbox.value;
  }
  showContent.value = false;
  currentTab.value = -1;
  emit('filterClose');
}

// 遮罩层点击
function handleMaskClick() {
  closeMenu();
}

// 获取所有选中值
function getAllValues() {
  // 返回与 defaultValues 长度相同的数组
  return selectedValues.value;
}

defineExpose({
  getAllValues,
  closeMenu
});
</script>

<style lang="scss" scoped>
.filter-menu {
  position: relative;
  width: 100%;
  
  .filter-header {
    display: flex;
    height: 88rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;
    position: relative;
    z-index: 101;
    
    .filter-title {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #333;
      
      &.active {
        color: #5FB961;
      }
    }
  }
  
  .filter-content {
    position: absolute;
    width: 100%;
    background: #fff;
    z-index: 100;
    transform: translateY(-100%);
    opacity: 0;
    transition: all 0.2s ease-out;
    
    &.content-show {
      transform: translateY(0);
      opacity: 1;
    }
    .menuBtnsWwrap{
      min-height: 600rpx;
    }
    
    .tree-filter {
      // height: 600rpx;
      
      .tree-wrapper {
        display: flex;
        height: 600rpx;
        
        .tree-column {
          flex: 1;
          height: 100%;
          border-right: 1rpx solid #eee;
          
          .tree-item {
            padding: 20rpx;
            font-size: 28rpx;
            
            &.active {
              color: #5FB961;
              background: #f5f5f5;
            }
          }
        }
      }
    }
    
    .radio-filter, .checkbox-filter {
      padding: 20rpx;
      
      .radio-item, .checkbox-item {
        display: inline-block;
        margin: 10rpx;
        padding: 10rpx 20rpx;
        border: 1rpx solid #ddd;
        border-radius: 4rpx;
        font-size: 28rpx;
        
        &.active {
          color: #5FB961;
          border-color: #5FB961;
          background: #f0f9f0;
        }
      }
    }
    
    .checkbox-footer {
      display: flex;
      padding: 20rpx;
      border-top: 1rpx solid #eee;
      
      .btn-reset, .btn-confirm {
        flex: 1;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        border-radius: 4rpx;
        margin: 0 10rpx;
      }
      
      .btn-reset {
        background: #f5f5f5;
        color: #666;
      }
      
      .btn-confirm {
        background: #5FB961;
        color: #fff;
      }
    }
  }
  
  .mask {
    position: fixed;
    top: var(--window-top, 0);
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0);
    z-index: 99;
    transform: translateY(88rpx);
    transition: background-color 0.2s ease-out;
    
    &.mask-show {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}
</style>
